
var express = require('express');
var router = express.Router();

const wishModel = require("../models/wish");

router.get('/list', function (req, res, next) {
  // get req.query
  // post req.body
  wishModel.find({}, (err, doc) => {
    if (err) throw err;
    res.json({
      status: 0,
      result: doc
    })
  })
});


// 收藏
router.post('/add', (req, res, next) => {
  const {
    id,
    url,
    locationurl,
    title,
    price,
    list,
    arr
  } = req.body;
  if (!id || !url || !locationurl || !title || !price || !arr) {
    res.json({
      status: 1,
      msg: '参数错误'
    })
  } else {
    // 构造一个用户的实例
    wishModel.findOne({ id: id }, (err, doc) => {
      if (err) throw err;
      if (!doc) {
        // 如果已经没有数据，存入数据库
        const wish = new wishModel({
          id,
          url,
          locationurl,
          title,
          price,
          list: list || '',
          arr,
        })
        // 存的是实例
        wish.save(err => {
          if (err) throw err;
          res.json({
            status: 0,
            msg: '新增成功',
          })
        })
      }
    })
  }
})


// 取消收藏
router.post('/del', (req, res, next) => {
  const { id } = req.body;
  if (!id) {
    res.json({
      status: 1,
      msg: '参数错误'
    })
  } else {
    wishModel.remove({ id: id }, err => {
      if (err) throw err;
      res.json({
        status: 0,
        msg: '删除成功'
      })
    })
  }
})

// 查询是否收藏
router.post('/check', (req, res, next) => {
  let { idlist } = req.body;
  if (typeof idlist !== 'object') {
    res.json({
      status: 1,
      msg: '参数错误'
    })
  } else {
    let num = 0;
    idlist.forEach((value, index) => {
      wishModel.findOne({ id: value }, (err, doc) => {
        if (err) throw err;
        if (doc) {
          idlist[index] = true;
        } else {
          idlist[index] = false;
        }
      })
        .then(() => {
          num++;
          if(num === idlist.length) {
            res.json({
              status: 0,
              result: idlist,
            })
          }
        })
    });
  }
})


module.exports = router;